package testrank.predictors;

import java.util.HashMap;
import java.util.Map;

import testrank.Conflict;

/**
 * @author Hagai Cibulski
 *
 */
public class RecursiveNormalizationUtil {
	public static void processScores(Map<Conflict, Double> scores, int nIterations, boolean startByTest) {
		for (int i = 1; i <= nIterations; i++) {
			normalize(scores, i % 2 == (startByTest ? 1 : 0));
		}
	}

	private static void normalize(Map<Conflict, Double> scores, boolean byTest) {
		
		Map<String, Double> sums = new HashMap<String, Double>();
		for (Conflict c : scores.keySet()) {
			String sig = getConflictPart(c, byTest);
			Double sum = sums.get(sig);
			if (sum == null) {
				sum = 0.0;
			}
			sum += scores.get(c);
			sums.put(sig, sum);
		}
		for (Conflict c : scores.keySet()) {
			String sig = getConflictPart(c, byTest);
			Double sum = sums.get(sig);
			assert sum != null;
			
			Double score = scores.get(c);
			Double val = score == 0.0 ? score : score / sum;
			assert 0.0 <= val && val <= 1.0 : "illegal val: " + val;
			scores.put(c, val);
		}
	}
	
	private static String getConflictPart(Conflict c, boolean isTest) {
		return isTest ? c.getTestSignature() : c.getMethodSignature();
	}
	
}
